package com.fivefu.core.parse;

import cn.hutool.core.util.StrUtil;
import com.fivefu.core.context.DynamicDataSourceContextHolder;
import com.fivefu.core.mapper.FfExecuteSqlMapper;
import com.fivefu.core.pojo.FfSql;
import com.fivefu.core.pojo.LayuiTable;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/8
 */
@Service
public class FfExecuteSql {


    @Autowired
    FfExecuteSqlMapper ffExecuteSqlMapper;

    public  Object executeFFSql(FfSql ffSql) {
        String key = StrUtil.isEmpty(ffSql.getDs()) ? "master" : ffSql.getDs();
        DynamicDataSourceContextHolder.setContextKey(key);
        //查询表信息
        List<Map<String, Object>> tables = ffExecuteSqlMapper.executeCommonSql(ffSql.createCommonSql());
        if (ffSql.getPageFlag()) {
            Integer count = ffExecuteSqlMapper.executeCountSql(ffSql.createCountSql());
            try {
                LayuiTable layuiTable = LayuiTable.renderSuccess(tables, count);
                return layuiTable;
            } catch (Exception e) {
                LayuiTable layuiTable = LayuiTable.renderError(e.getMessage());
                return layuiTable;
            }finally {
                DynamicDataSourceContextHolder.removeKey();
            }
        }
        DynamicDataSourceContextHolder.removeKey();
        return  tables;

    }

}
